<template>
  <div>
    <medicalCard title="轮播管理">
      <template v-slot:body>
        <template>
          <Button icon="md-add" type="success" class="headFormItemButton" @click="add()">新增</Button>
          <Button icon="md-trash" type="error" class="headFormItemButton" @click="delList">删除</Button>
        </template>
        <vxe-table border="outer" header-align="center" ref="my_table"
                   :loading="loading"
                   :data="tableData"
                   :stripe="true"
                   style="margin-top: 5px;margin-bottom: 10px"
                   :highlight-hover-row="true"
                   :scroll-x="{gt: 0}" align="center" show-overflow="tooltip">
          <vxe-table-column width="60" fixed="left" type="checkbox"></vxe-table-column>
          <vxe-table-column field="city" fixed="left" title="城市" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.city | TypeFilter(cityList)}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column  title="图片" min-width="200">
            <template v-slot="{ row }">
              <img :src="row.picture" preview width="40px" height="40px" />
            </template>
          </vxe-table-column>
          <vxe-table-column field="position" title="位置" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.position | TypeFilter(positionList)}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="type" title="类型" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.client_type | TypeFilter(clientTypeList)}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="type" title="跳转类型" min-width="200">
            <template v-slot="{ row }">
              <span>{{row.type | TypeFilter(typeList)}}</span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="url" title="网址" min-width="200"></vxe-table-column>
          <vxe-table-column field="sort" title="排序" min-width="200">
            <template v-slot="{ row }">
              <Poptip v-model="row.poptipVisible" placement="top" style="z-index: 9999" :transfer='true'>
                <a href="javascript:void(0);" style="color: #2D8cF0;" @click="row.newSort = row.sort">{{row.sort}}</a>
                <template #content>
                  <Input type="text" clearable v-model="row.newSort" class="headFormItemWidth" />
                  <Button type="success"  icon="md-checkmark" style="padding: 0;margin-left: 2px" @click="editSort(row)"></Button>
                  <Button icon="md-close" style="padding: 0;margin-left: 2px" @click="row.poptipVisible = false"></Button>
                </template>
              </Poptip>
            </template>
          </vxe-table-column>
          <vxe-table-column field="state" title="状态" min-width="200">
            <template v-slot="{ row }">
              <i-Switch v-model="row.state" size="large" true-color="#13ce66" false-color="#ff4949" true-value="1" false-value="2" @on-change="editState(row)">
                <template #open>
                  <span>开启</span>
                </template>
                <template #close>
                  <span>关闭</span>
                </template>
              </i-Switch>
            </template>
          </vxe-table-column>
          <vxe-table-column width="100" fixed="right" title="操作">
          <template scp-layout="true" v-slot="{ row }">
            <ButtonGroup>
              <Button type="warning" icon="md-create" style="padding: 0" @click="edit(row)"></Button>
              <Button type="error" icon="md-trash" style="padding: 0" @click="del(row)"></Button>
            </ButtonGroup>
          </template>
          </vxe-table-column>
        </vxe-table>
        <Row type="flex" justify="end">
          <Page :current="params.pageNo" :total="params.totalRecord" show-sizer :page-size="params.pageSize" show-elevator
                @on-change="pageAction" @on-page-size-change="pageSizeChange"/>
        </Row>
      </template>
    </medicalCard>
    <Modal v-model="modal.show" draggable sticky scrollable :closable="false" :mask="false" :title="modal.title" width="750">
      <div style="overflow:overlay;height: 600px">
        <Form :modal="modal.data" ref="formInline" :label-width="70" label-colon >
          <Row>
            <Col span="23">
              <FormItem label="城市">
                <Select v-model="modal.data.city" @on-select="selectCity">
                  <Option v-for="(item, index) in cityList" :value="item.value" :tag="JSON.stringify(item)" v-bind:key="index">{{item.label}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="23">
              <FormItem label="图片">
                <Row class="bench_search">
                  <div class="demo-upload-list" v-for="(item,index) in imgList" :key="index">
                    <img :src="item">
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                  </div>
                  <Upload
                    ref="upload"
                    :show-upload-list="false"
                    :format="['jpg','jpeg','png']"
                    :max-size="2048"
                    :before-upload="handleBeforeUpload"
                    multiple
                    type="drag"
                    action="//jsonplaceholder.typicode.com/posts/"
                    style="display: inline-block;width:58px;">
                    <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                  </Upload>
                  <Modal title="查看图片" v-model="visible">
                    <img :src="imgListShow" v-if="visible" style="width: 100%">
                    <div slot="footer">
                      <div>
                        <Button @click="visible = false" type="text" class="cancel_btn">取消</Button>
                      </div>
                    </div>
                  </Modal>
                </Row>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="23">
              <FormItem label="状态" style="float: left;width: 100%">
                <RadioGroup v-model="modal.data.state">
                  <Radio label="1">开启</Radio>
                  <Radio label="2">关闭</Radio>
                </RadioGroup>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="23">
              <FormItem label="排序" prop="sort" style="width: 100%">
                <Input v-model="modal.data.sort" @on-keyup="checkNumber"></Input>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="23">
              <FormItem label="类型" style="width: 100%">
                <Select v-model="modal.data.client_type">
                  <Option v-for="(item, index) in clientTypeList" v-bind:key="index" :value="item.value">{{item.label}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="modal.data.client_type == '1'">
            <Col span="23">
              <FormItem label="跳转类型" style="width: 100%">
                <Select v-model="modal.data.type" @on-change="changeType">
                  <Option v-for="(item, index) in typeList" v-bind:key="index" :value="item.value">{{item.label}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="modal.data.type === '2'">
            <Col span="23">
              <FormItem label="医院" style="width: 100%">
                <Select v-model="modal.data.hospital_id">
                  <Option v-for="(item, index) in hospitalList" v-bind:key="index" :value="item.hospital_id">{{item.hospital_name}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="modal.data.type === '5'">
            <Col span="23">
              <FormItem label="服务类型" style="width: 100%">
                <Select v-model="modal.data.service_type" clearable filterable>
                  <Option v-for="(item, index) in serviceTypeList" v-bind:key="index" :value="item.value">{{item.label}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="23">
              <FormItem label="位置" style="width: 100%">
                <Select v-model="modal.data.position">
                  <Option v-for="(item, index) in positionList" v-bind:key="index" :value="item.value">{{item.label}}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="modal.data.type == '1'">
            <Col span="23">
              <FormItem label="跳转网址">
                <Input v-model="modal.data.url" clearable style="width: 100%;" />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <template #footer>
        <Button @click="modal.show = false">取消</Button>
        <Button type="primary" @click="addOk()">确定</Button>
      </template>
    </Modal>
  </div>

</template>

<script>
import medicalCard from '@/view/medical-page/components/medical-card'
import {
  insertRotationChart,
  updateRotationChart,
  findRotationChartList,
  getSign,
  createUpLoadFiles,
  deleteRotationChart,
  getHospitalList
} from '@/api/medical'
export default {
  name: 'hospital-list',
  components: {
    medicalCard
  },
  data () {
    return {
      showFlag: false,
      location: {
        lng: 123.412581,
        lat: 41.805853
      },
      lng: null,
      lat: null,
      map: null,
      marker: null,
      options: [],
      inputSearch: '',
      coordinate: '',
      loading1: false,
      loading: false,
      imgList: [],
      visible: false,
      poptipVisible: false,
      imgListShow: '',
      modal: {
        show: false,
        type: null,
        data: {},
        title: ''
      },
      params: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      },
      tableData: [],
      cityList: [
        { label: '沈阳市', value: '210100' }
      ],
      selectList: [],
      positionList: [
        { label: '用户页面', value: '1' },
        // { label: '陪诊机构页面', value: '2' },
        { label: '陪诊师页面', value: '3' },
        { label: '广告位', value: '4' }
      ], // 位置
      typeList: [
        { label: '网址', value: '1' },
        { label: '医院', value: '2' },
        // { label: '陪诊机构', value: '3' },
        // { label: '陪诊师', value: '4' },
        { label: '服务', value: '5' }
      ], // 跳转类别
      clientTypeList: [
        { label: '用户端', value: '1' },
        // { label: '机构端', value: '2' },
        { label: '陪诊端', value: '3' }
      ],
      hospitalList: '', // 医院下拉
      serviceTypeList: [
        { label: '诊前预约', value: '诊前预约' },
        { label: '代办问诊', value: '代办问诊' },
        { label: '代办买药', value: '代办买药' },
        { label: '送取结果', value: '送取结果' },
        { label: '就医陪诊', value: '就医陪诊' },
        { label: '就医陪诊（单）', value: '就医陪诊（单）' },
        { label: '院内陪护', value: '院内陪护' }
      ]
    }
  },
  computed: {
  },
  inject: [
    'reload'
  ],
  filters: {
    TypeFilter: function (value, array) {
      let name = ''
      array.forEach(item => {
        if (item.value === value) {
          name = item.label
        }
      })
      return name
    }
  },
  methods: {
    search () {
      this.params.pageNo = 1
      this.params.totalRecord = 0
      this.init()
    },
    init () {
      this.loading = true
      findRotationChartList(this.params).then(ret => {
        if (ret.data.errcode === 0) {
          this.tableData = ret.data.data.results
          // this.tableData.forEach(element => {
          //   element.city = '沈阳'
          // })
          this.params.totalRecord = ret.data.data.totalRecord
          this.loading = false
        } else {
          this.$Message.error(ret.data.errmsg)
        }
      })
    },
    selectCity (value) {
      console.log(value, '$$$$$')
      this.modal.data.code_name = JSON.parse(value.tag).label
      this.modal.data.city_code = JSON.parse(value.tag).value
      this.modal.data.city = JSON.parse(value.tag).value
    },
    del (row) {
      this.$Modal.confirm({
        title: '<p style="color:#f60;text-align:center">\n' +
          '                    <Icon type="ios-information-circle"></Icon>\n' +
          '                    <span>删除操作</span>\n' +
          '                </p>',
        content: '<p>确定要执行该操作吗？</p>',
        width: 300,
        loading: true,
        onOk: () => {
          deleteRotationChart({ rotationChartList: [{ id: row.id }] }).then(ret => {
            if (ret.data.errcode === 0) {
              this.$Message.success({
                content: '操作成功,\n' + ret.data.errmsg
              })
              this.init()
            } else {
              this.$Message.error({
                content: '操作失败,\n' + ret.data.errmsg
              })
            }
          })
          this.$Modal.remove()
        }
      })
    },
    add () {
      // this.initMap(this.location)
      this.modal.data = {}
      this.coordinate = ''
      this.inputSearch = ''
      this.selectList = []
      // this.selectCityList()
      this.modal.title = '新增'
      this.modal.type = 0
      this.modal.show = true
    },
    editSort (row) {
      let params = {
        hospital_id: row.hospital_id,
        sort: row.newSort
      }
      this.updateInfo(params)
    },
    editState (row) {
      let params = {
        id: row.id,
        state: row.state
      }
      this.updateInfo(params)
    },
    edit (row) {
      console.log(row, 'row')
      this.getHospitalData()
      this.modal.data = row
      console.log(this.modal.data.city, '5555')
      if (row.picture) {
        this.imgList = [row.picture]
      }
      this.modal.title = '修改'
      this.modal.type = 1
      this.modal.show = true
    },
    addOk () {
      if (!this.modal.data.client_type) {
        this.$Message.error({
          content: '请选择类型'
        })
        return false
      }
      if (this.modal.data.client_type === '1' && !this.modal.data.type) {
        this.$Message.error({
          content: '请选择跳转类型'
        })
        return false
      }
      if (this.modal.data.type === '1' && !this.modal.data.url) {
        this.$Message.error({
          content: '请填写跳转网址'
        })
        return false
      }
      if (this.modal.data.type === '2' && !this.modal.data.hospital_id) {
        this.$Message.error({
          content: '请选择医院'
        })
        return false
      }
      if (this.modal.data.type === '5' && !this.modal.data.service_type) {
        this.$Message.error({
          content: '请选择服务类型'
        })
        return false
      }
      if (this.imgList.length > 0) {
        this.modal.data.picture = this.imgList[0]
      }
      if (!this.modal.data.id) {
        insertRotationChart(this.modal.data).then(ret => {
          if (ret.data.errcode === 0) {
            this.modal.show = false
            this.$Message.success({
              content: '操作成功,\n' + ret.data.errmsg
            })
            this.init()
          } else {
            this.$Message.error({
              content: '操作失败,\n' + ret.data.errmsg
            })
          }
        })
      }
      if (this.modal.data.id) {
        this.updateInfo(this.modal.data)
      }
    },
    updateInfo (e) {
      updateRotationChart(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.modal.show = false
          this.$Message.success({
            content: '操作成功,\n' + ret.data.errmsg
          })
          this.init()
        } else {
          this.$Message.error({
            content: '操作失败,\n' + ret.data.errmsg
          })
        }
      })
    },
    delList () {
      let selectRecords = this.$refs.my_table.getCheckboxRecords()
      if (!selectRecords || selectRecords.length === 0) {
        this.$Message.error({
          content: '操作失败,\n' + '请选择删除项'
        })
        return
      }
      let array = []
      selectRecords.forEach(element => {
        array.push({ id: element.id })
      })
      // let array = selectRecords.map((item) => item.id)
      this.$Modal.confirm({
        title: '<p style="color:#f60;text-align:center">\n' +
          '                    <Icon type="ios-information-circle"></Icon>\n' +
          '                    <span>删除操作</span>\n' +
          '                </p>',
        content: '<p>确定要执行该操作吗？</p>',
        width: 300,
        loading: true,
        onOk: () => {
          deleteRotationChart({ rotationChartList: array }).then(ret => {
            if (ret.data.errcode === 0) {
              this.$Message.success({
                content: '操作成功,\n' + ret.data.errmsg
              })
              this.init()
            } else {
              this.$Message.error({
                content: '操作失败,\n' + ret.data.errmsg
              })
            }
          })
          this.$Modal.remove()
        }
      })
    },
    initMap (e) {
      this.map = new AMap.Map('mapHospitalAddress', {
        resizeEnable: true,
        center: new AMap.LngLat(e.lng, e.lat),
        zoom: 16
      })
      this.map.on('click', this.clickHandler)
      // this.createMaker(e)
      let _this = this
      AMap.plugin('AMap.ToolBar', function () { // 异步加载插件
        var toolbar = new AMap.ToolBar()
        _this.map.addControl(toolbar)
      })
      AMap.plugin('AMap.Scale', function () { // 异步加载插件
        var scale = new AMap.Scale()
        _this.map.addControl(scale)
      })
      this.clearMarker()
      this.createMaker(e)
    },
    createMaker (e) {
      this.coordinate = e.lng + ',' + e.lat
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(e.lng, e.lat)
      })
      this.map.setCenter(new AMap.LngLat(e.lng, e.lat))
      this.map.add(this.marker)
    },
    clickHandler (e) {
      this.lng = e.lnglat.lng
      this.lat = e.lnglat.lat
      let data = {
        lng: this.lng,
        lat: this.lat
      }
      this.clearMarker()
      this.createMaker(data)
    },
    clearMarker () {
      if (this.marker) {
        this.marker.setMap(null)
        this.marker = null
      }
    },
    selectAddress (e) {
      console.log(e, '0000')
      if (!JSON.parse(e.tag).location) return
      this.clearMarker()
      this.createMaker(JSON.parse(e.tag).location)
    },
    autoInput (keywords) {
      if (!keywords) return
      let _this = this
      let autoOptions = {
        city: '全国'
      }
      let autoComplete = new AMap.Autocomplete(autoOptions)
      autoComplete.search(keywords, function (status, result) {
        if (result) {
          _this.options = result.tips
        }
        console.log(_this.options, 'kkkkkk')
      })
    },
    pageAction (page) {
      this.params.pageNo = page
      this.init()
    },
    pageSizeChange (e) {
      this.params.pageSize = e
      this.init()
    },
    handleView (img) {
      this.imgListShow = img
      this.visible = true
    },
    handleRemove (file) {
      this.imgList.splice(this.imgList.indexOf(file), 1)
    },
    handleBeforeUpload (file) {
      // const check = this.imgList.length < 1
      // if (!check) {
      //   this.$Notice.warning({
      //     title: '最多上传1张图片'
      //   })
      //   return check
      // }
      this.beforeUpload(file)
    },
    beforeUpload (file) {
      let upPicData = {}
      // upPicData.filePath = 'medical/hospital/images'
      upPicData.filePath = 'medical/banner/images'
      upPicData.fileName = this.modal.data.hospital_name ? this.modal.data.hospital_name : '轮播图片'
      var time = new Date().getTime()
      let timestamp = time.toString()
      upPicData.timestamp = timestamp
      let that = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        let index = reader.result.indexOf('base64,') + 7
        upPicData.fileName = upPicData.fileName + timestamp + '.' + file.type.substring(6)
        upPicData.file = reader.result.substring(index)
        that.upPic(upPicData)
      }
      return false
    },
    upPic (fileData) {
      getSign({
        filePath: fileData.filePath,
        fileName: fileData.fileName,
        timestamp: fileData.timestamp
      }).then(res => {
        if (res.data.errcode === 0) {
          createUpLoadFiles(res.data.data.docking_url, {
            sign: res.data.data.sign,
            timestamp: fileData.timestamp,
            filePath: fileData.filePath,
            fileName: fileData.fileName,
            file: fileData.file
          }).then(ret => {
            if (ret.data.errcode === 0) {
              this.imgList = [ret.data.data]
              this.modal.data.picture = this.imgList[0]
              this.$Message.success({
                content: '上传成功,\n' + ret.data.errmsg
              })
            } else {
              this.$Message.error({
                content: '上传失败,\n' + ret.data.errmsg
              })
            }
          })
        }
      })
    },
    checkNumber () { // 排序字段正整数校验
      if (this.modal.data.sort === '0') {
        this.modal.data.sort = ''
      } else {
        this.modal.data.sort = this.modal.data.sort.replace(/\D/g, '')
      }
    },
    getHospitalData () {
      if (this.modal.data.type === '2') {
        getHospitalList({}).then(res => {
          if (res.data.errcode === 0) {
            this.hospitalList = res.data.data
          }
        })
      }
    },
    changeType () {
      this.getHospitalData()
    }
  },
  watch: {
  },
  mounted () {
    this.init()
    this.getHospitalData()
  }
}
</script>
<style scoped>
#mapHospitalAddress {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 500px;
}
.headFormItemWidth{
  width: 200px;
}
.headFormItemButton{
  margin-right: 10px;
}
.formItem{
  float: right;
}
</style>
